{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "56341c66",
   "metadata": {},
   "source": [
    "# Chapter 0: Compiling and Running Toy\n",
    "\n",
    "Here is a simple program in the Toy programming language running in a RISC-V emulator, \n",
    "compiled using xDSL.\n",
    "Try changing the program and observing the output:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e07ae44f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]\n",
      "[[2.0, 4.0, 6.0], [8.0, 10.0, 12.0]]\n"
     ]
    }
   ],
   "source": [
    "from toy.compiler import compile, emulate_riscv\n",
    "\n",
    "from xdsl.utils.exceptions import VerifyException\n",
    "\n",
    "program = \"\"\"\n",
    "def main() {\n",
    "  # Define a variable `a` with shape <2, 3>, initialized with the literal value.\n",
    "  # The shape is inferred from the supplied literal.\n",
    "  var a = [[1, 2, 3], [4, 5, 6]];\n",
    "\n",
    "  # The literal tensor is implicitly reshaped: defining new variables is the way\n",
    "  # to reshape tensors (element count must match).\n",
    "  var b<3, 2> = [1, 2, 3, 4, 5, 6];\n",
    "\n",
    "  # There is a built-in print instruction to display the contents of the tensor\n",
    "  print(b);\n",
    "\n",
    "  # Reshapes are implicit on assignment\n",
    "  var c<2, 3> = b;\n",
    "\n",
    "  # There are + and * operators for pointwise addition and multiplication\n",
    "  var d = a + c;\n",
    "\n",
    "  print(d);\n",
    "}\n",
    "\"\"\"\n",
    "\n",
    "try:\n",
    "    code = compile(program)\n",
    "    emulate_riscv(code)\n",
    "except VerifyException as e:\n",
    "    print(e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "39a4b4ea",
   "metadata": {},
   "source": [
    "It is also possible to use MLIR + LLVM to compile and execute Toy natively on your machine.\n",
    "For this to work, MLIR and LLVM need to be built from source with the commit specified in the README, and the binaries used below must be in the path."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "3af9c75a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Uncomment the following lines to execute\n",
    "# !python -m toy examples/interpret.toy --emit=scf --ir \\\n",
    "# | xdsl-opt -p printf-to-llvm \\\n",
    "# | mlir-opt --test-lower-to-llvm \\\n",
    "# | mlir-cpu-runner --entry-point-result=void"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
